package aex.action;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import aex.domain.Article;
import aex.domain.ArticleCategory;
import aex.domain.AttentionUser;
import aex.domain.CategoryEditer;
import aex.domain.CommentArticle;
import aex.domain.CommentMedicines;
import aex.domain.CommentTherapy;
import aex.domain.Medicines;
import aex.domain.MessageBoard;
import aex.domain.Operation;
import aex.domain.Puser;
import aex.domain.Score;
import aex.domain.ShowPoint;
import aex.domain.Therapy;
import aex.service.ArticleCategoryService;
import aex.service.ArticleService;
import aex.service.AttentionUserService;
import aex.service.CategoryEditerService;
import aex.service.CommentArticleService;
import aex.service.CommentMedicinesService;
import aex.service.CommentTherapyService;
import aex.service.MedicinesService;
import aex.service.MessageBoardService;
import aex.service.OperationService;
import aex.service.PuserService;
import aex.service.ScoreService;
import aex.service.ShowBoxService;
import aex.service.ShowPointService;
import aex.service.TherapyService;
import aex.util.CU;
import aex.util.Constant;
import aex.util.PageBean;
import aex.util.Ptool;

@Controller("VisitorAction")
@Scope("prototype")
public class VisitorAction extends BaseActon  {

	private static final long serialVersionUID = 1L;


	@Resource(name = ArticleCategoryService.SERVICE_NAME)
	ArticleCategoryService acService;
	
	@Resource(name = CategoryEditerService.SERVICE_NAME)
	CategoryEditerService ceService;
	
	@Resource(name = MedicinesService.SERVICE_NAME)
	MedicinesService medicinesService;
	
	@Resource(name = PuserService.SERVICE_NAME)
	PuserService puserService;
	
	
	@Resource(name = ArticleService.SERVICE_NAME)
	ArticleService artService;

	@Resource(name = CommentArticleService.SERVICE_NAME)
	CommentArticleService comaService;
	
	@Resource(name = CommentMedicinesService.SERVICE_NAME)
	CommentMedicinesService commService;
	
	
	@Resource(name = CommentTherapyService.SERVICE_NAME)
	CommentTherapyService comtService;
	
	@Resource(name = TherapyService.SERVICE_NAME)
	TherapyService therapytService;
	
	
	

	
	@Resource(name = ShowBoxService.SERVICE_NAME)
	ShowBoxService sbService;
	
	@Resource(name = ShowPointService.SERVICE_NAME)
	ShowPointService spService;
	
	@Resource(name = AttentionUserService.SERVICE_NAME)
	AttentionUserService auService;
	
	@Resource(name = MessageBoardService.SERVICE_NAME)
	MessageBoardService mbService;
	
	@Resource(name = ScoreService.SERVICE_NAME)
	ScoreService  scoreService;
	
	@Resource(name = OperationService.SERVICE_NAME)
	OperationService opService;


	public VisitorAction() {
		CU.deBugPrintln("VisitorAction 被创建");
	}

	/**
	 * 进入小组列表
	 * @return
	 */
	public String categoryList(){
		request.setAttribute("categorys",acService.findAllNoPage());
		return "categoryList";
	}
	
	
	/**
	 * 申请加入某一个小组
	 * @return
	 */
	public String joinCategory(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			ajaxPrint("visitorPage/login.jsp");
			return null;
		}else{
			String id=request.getParameter("acId");
			ArticleCategory cate=acService.findByID(id);
			cate.setAcUserNum(cate.getAcUserNum()+1);
			acService.update(cate);
			CategoryEditer ce=new CategoryEditer();
			ce.setArticleCategory(cate);
			ce.setPuser(user);
			ceService.save(ce);
			
			changeScore(user,Constant.SCORE_JRXZ);
			
			user.getCategoryEditers().add(ce);
			request.setAttribute("categorys",acService.findAllNoPage());
			
			if(request.getParameter("type")==null){//从列表页加入
			ajaxPrint("ok");
			return null;
			
			}else{//从详细页加入
				String id1=request.getParameter("acId");
				ArticleCategory cate1=acService.findByID(id1);
				request.setAttribute("category",cate1);
				//准备文章数据
				PageBean<Article> pageBean = new PageBean<Article>();
				PageBean.initPageBean(pageBean, request,"&id="+id1);
				pageBean.setPageSize(8);
				pageBean = artService.findByCategory(pageBean,id1);
				request.setAttribute("pageBean", pageBean);
				ajaxPrint("ok");
				return null;
			}
		}
	}
	
	/**
	 * 退出某个小组
	 * @return
	 */
	public String outCategory(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			ajaxPrint("visitorPage/login.jsp");
			return null;
		}else{
			
			String id=request.getParameter("acId");
			ArticleCategory cate=acService.findByID(id);
			cate.setAcUserNum(cate.getAcUserNum()-1);//更新小组人数
			acService.update(cate);
			request.setAttribute("category",cate);
			CategoryEditer ce= ceService.findByUserAndCategory(user.getPuId(),cate.getAcId());
			if(ce!=null){
				Set<CategoryEditer> set=user.getCategoryEditers();
				for (CategoryEditer categoryEditer : set) {
					if(categoryEditer.getCeId().equals(ce.getCeId())){
						set.remove(categoryEditer);
						break;
					}
				}
				ceService.deleteById(ce.getCeId());;
				
				changeScore(user,Constant.SCORE_TCXZ);
				
			}
			//准备文章数据
			PageBean<Article> pageBean = new PageBean<Article>();
			PageBean.initPageBean(pageBean, request,"&id="+id);
			pageBean.setPageSize(8);
			pageBean = artService.findByCategory(pageBean,id);
			request.setAttribute("pageBean", pageBean);
			ajaxPrint("ok");
			return null;
		}
	}
	
	/**
	 * 进入栏目文章列表页
	 * @return
	 */
	public String showCategory(){
		String id=request.getParameter("id");
		PageBean<Article> pageBean = new PageBean<Article>();
		PageBean.initPageBean(pageBean, request,"&id="+id);
		pageBean.setPageSize(8);
		pageBean = artService.findByCategory(pageBean,id);
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("category", acService.findByID(id));
		return "showCategory";
	}

	/**
	 * 我要发布帖子
	 * @return
	 */
	public String addArticle(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		String id=request.getParameter("acId");
		ArticleCategory cate=acService.findByID(id);
		if(user==null){
			return "login";
		}else{
			if(!Ptool.userIsInCategory(user.getCategoryEditers(), cate)){
				return CU.goMsgPage(request, "本小组只允许小组成员发贴，请加入小组后再发帖！", "err", "javascript:history.go(-1);");
			}else{
				request.setAttribute("category", cate);
				return "userAddArticle";
			}
			
			
		}
	}
	
	/**
	 * 从用户空间开始给对方发送消息
	 * @return
	 */
	public String sendMailFromHerHome(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			return "login";
		}else{
			int id=Integer.parseInt(request.getParameter("herId"));
			request.setAttribute("her", puserService.findById(id));
			return "sendMail";
		}
	}
	
	
	/**
	 * 查看某一个文章
	 * @return
	 */
	public String article() {
		int arId =Integer.parseInt(request.getParameter("arId"));
		Article art = artService.findByID(arId);
		art.setArViewCount(art.getArViewCount()+1);
		artService.update(art);
		//取出文章所属分类 最第一级分类直到最高一级都取出来
		request.setAttribute("art", art);
		request.setAttribute("prev",
				artService.findPrev(arId, art.getArticleCategory().getAcId()));
		request.setAttribute("next",
				artService.findNext(arId, art.getArticleCategory().getAcId()));
		
		PageBean<CommentArticle> pageBean = new PageBean<CommentArticle>();
		PageBean.initPageBean(pageBean, request,"&arId="+arId);
		pageBean = comaService.findByArticle(pageBean,arId);
		request.setAttribute("pageBean", pageBean);
		return "article";
	}
	

	/**
	 * 点击喜欢文章
	 * @return
	 */
	public String top() {
		@SuppressWarnings("unchecked")
		HashSet<Integer> isToped=(HashSet<Integer>) request.getSession().getAttribute("isToped");
		int artId=Integer.parseInt(request.getParameter("arId"));
		if(isToped==null){
			isToped=new HashSet<Integer>();
			request.getSession().setAttribute("isToped", isToped);
		}
		if(isToped.contains(artId)){
			ajaxPrint("每天只能顶一次！");
		}else{
			Article art=artService.findByID(artId);	
			art.setArLike(art.getArLike()+1);
			artService.update(art);
			isToped.add(artId);
			request.getSession().setAttribute("isToped", isToped);
			ajaxPrint("ok");
		}
		return null;
	}
	
	
	/***
	 * 这个添加评论的方法不知道为什么会自动吧自己设置为父级评论？
	 * 请以后解决！
	 * @return
	 */
	public Integer arId;
	public String addComment() {
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			return "login";
		}
		 arId = Integer.parseInt(request.getParameter("arId"));
		Integer acId = null;
		String acIdStr = request.getParameter("acId");
		if (acIdStr != null) {
			acId = Integer.parseInt(acIdStr);
		}
		Article art = artService.findByID(arId+"");
		CU.deBugPrintln(art+"----"+arId);
		art.setArComentCount(
				art.getArComentCount()
				+1);
		artService.update(art);
		CommentArticle comment = new CommentArticle();
		if (acId == null) {// 对文章进行评论
			comment.setCaTime(CU.getSqlTime());
			comment.setPuser(user);
			comment.setArticle(art);
			comment.setCaCount(request.getParameter("comment").replaceAll("<", "&lt").replaceAll(">", "&gt"));
		} else {// 对评论进行评论
			CommentArticle targetCom= comaService.findByID(acId);
			comment.setCaTime(CU.getSqlTime());
			comment.setPuser(user);
			comment.setCaCount("【"+comment.getPuser().getPuName()+"】回复： 【" +targetCom.getPuser().getPuName()+"】<br><br>"+ request.getParameter("comment").replaceAll("<", "&lt").replaceAll(">", "&gt"));
			comment.setCommentArticle(targetCom.getTopComment());//对子评论的评论也会看做对父评论的评论
		}
		// 对评论进保存
		comaService.save(comment);
		
		changeScore(user,Constant.SCORE_FBHF);
		
		Puser her=her=art.getPuser();
		
		
		
		// 返回原页面
		request.setAttribute("art", art);
		request.setAttribute("prev",
				artService.findPrev(arId, art.getArticleCategory().getAcId()));
		request.setAttribute("next",
				artService.findNext(arId, art.getArticleCategory().getAcId()));
		return "commentAover";
	}
	
	

	
	
	
	/**
	 * 主题页面
	 * @return
	 */
	public String themePage(){
		PageBean<ShowPoint> pageBean = new PageBean<ShowPoint>();
		PageBean.initPageBean(pageBean, request,"");
		pageBean = spService.findPointByName("专题",pageBean );
		request.setAttribute("pageBean", pageBean);
		return "themePage";
	}
	
	
	
	/**
	 * 进入其他用户的空间
	 * @return
	 */
	public String herHome(){
		
		Puser her=puserService.findById(Integer.parseInt(request.getParameter("id")));
		Puser my=(Puser) request.getSession().getAttribute("user");
		PageBean<Article> pageBean = new PageBean<Article>();
		PageBean.initPageBean(pageBean, request,"&id="+her.getPuId()+"&pageSize=20");
		
		if(my!=null&&my.getPuId().equals(her.getPuId())){
			pageBean = artService.findByUser(pageBean,my.getPuId());
			request.setAttribute("pageBean", pageBean);
			return "myHome";
			
		}else{
			
			pageBean = artService.findByUser(pageBean,her.getPuId());
			request.setAttribute("pageBean", pageBean);
			request.setAttribute("her", her);
			return "herHome";
		}
	}
	
	
	

	/**
	 * 关注某人
	 * @return
	 */
	public String attentionUser(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			ajaxPrint("visitorPage/login.jsp");
			return null;
		}else{
			String id=request.getParameter("id");
			Puser her=puserService.findById(Integer.parseInt(id));
			user.setPuAttention(her.getPuAttention()+1);
			her.setPuFans(her.getPuFans()+1);
			AttentionUser au=new AttentionUser();
			au.setPuserByAuAattentiond(her);
			au.setPuserByAuAttention(user);
			auService.save(au);
			user.getAttentionUsersForAuAttention().add(au);
			
			changeScore(user,Constant.SCORE_GZJY);
			
			
			puserService.update(user);
			puserService.update(her);
			ajaxPrint("ok");
				return null;
			}
		}
	
	
	
	
	
	
	
	/**
	 * 取消关注某人
	 * @return
	 */
	public String unattentionUser(){
		
			Puser user=(Puser) request.getSession().getAttribute("user");
			String id=request.getParameter("id");
			Puser her=puserService.findById(Integer.parseInt(id));
			user.setPuAttention(her.getPuAttention()-1);
			her.setPuFans(her.getPuFans()-1);
			
			
			Set<AttentionUser> set=user.getAttentionUsersForAuAttention();
			
			for (AttentionUser attentionUser : set) {
				CU.deBugPrintln(attentionUser.getPuserByAuAattentiond().getPuName()+"   ed");
				CU.deBugPrintln(attentionUser.getPuserByAuAttention().getPuName()+"    e");
				if(attentionUser.getPuserByAuAattentiond().getPuId().equals(her.getPuId())){
					//要同时删除两方的关系后才能解除级联删除报错！
					set.remove(attentionUser);
					user.getAttentionUsersForAuAattentiond().remove(attentionUser);
					changeScore(user,Constant.SCORE_QXGZ);
					
					puserService.update(user);
					puserService.update(her);
					auService.deleteById(attentionUser.getAuId());
					break;
				}
			}
			
			ajaxPrint("ok");
			return null;
		
	}
	
	
	
	
	/**
	 * 添加留言
	 */
	public String addLy(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		Puser her=puserService.findById(
				Integer.parseInt(
						request.getParameter("id")));
		if(user==null){
			return "login";
		}else{
			
			MessageBoard ly=new MessageBoard();
			ly.setMbTime(CU.getSqlTime());
			ly.setPuserByMbPu(user);
			ly.setPuserByMbPued(her);
			ly.setMbContent(request.getParameter("content"));
			changeScore(user,Constant.SCORE_TJLY);
			mbService.save(ly);
		}
		return CU.goMsgPage(request, "添加留言成功！", "ok", "visitor/visitor_herHome.do?id="+her.getPuId());
	}
	
	
	
	
	
	/**
	 * 进如药品列表页
	 */
	public String medicineList(){
		request.setAttribute("category",acService.
				findByID(
						request.getParameter("id")));
		return "medicineList";
	}
	
	
	/**
	 * 进如疗效列表页
	 */
	public String therapyList(){
		request.setAttribute("category",acService.
				findByID(
						request.getParameter("id")));
		return "therapyList";
	}
	
	

	/**
	 * 进如药品详细页
	 */
	public String medicine(){
		request.setAttribute("medicine",medicinesService.
				findByID(
						request.getParameter("id")));
		
		PageBean<CommentMedicines> pageBean = new PageBean<CommentMedicines>();
		PageBean.initPageBean(pageBean, request,"&id="+request.getParameter("id"));
		pageBean=commService.findByCategory(pageBean,Integer.parseInt(request.getParameter("id")));
		CU.deBugPrintln("获取了药品评论 ："+pageBean.getObjList().size());
		request.setAttribute("pageBean", pageBean);
		return "medicine";
	}
	
	
	/**
	 * 进如疗效详细页
	 */
	public String therapy(){
		request.setAttribute("therapy",therapytService.
				findByID(
						request.getParameter("id")));
		PageBean<CommentTherapy> pageBean = new PageBean<CommentTherapy>();
		PageBean.initPageBean(pageBean, request,"&id="+request.getParameter("id"));
		pageBean=comtService.findByCategory(pageBean,Integer.parseInt(request.getParameter("id")));
		request.setAttribute("pageBean", pageBean);
		return "therapy";
	}
	
	
	/**
	 * 添加药品评论
	 */
	public String addCommentMedicines(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			return "login";
		}else{
			CommentMedicines com=new CommentMedicines();
			Medicines medicines=medicinesService.findByID(request.getParameter("id"));
			com.setMedicines(medicines);
			com.setPuser(user);
			com.setCmContent(request.getParameter("content"));
			com.setCmEffect(Integer.parseInt(request.getParameter("effect")));
			com.setCmPice(Integer.parseInt(request.getParameter("pice")));
			com.setCmSafe(Integer.parseInt(request.getParameter("safe")));
			com.setCmTime(CU.getSqlTime());
			commService.save(com);
			return CU.goMsgPage(request, "评论成功！", "ok", "visitor/visitor_medicine.do?id="+medicines.getMeId());	
		}
	}
	
	
	

	/**
	 * 添加疗效评论
	 */
	public String addCommentTherapy(){
		Puser user=(Puser) request.getSession().getAttribute("user");
		if(user==null){
			return "login";
		}else{
			CommentTherapy com=new CommentTherapy();
			Therapy therapy=therapytService.findByID(request.getParameter("id"));
			com.setTherapy(therapy);
			com.setPuser(user);
			com.setCtContent(request.getParameter("content"));
			com.setCtUse(request.getParameter("isHelp").equals("1")?"有帮助":"帮助");
			com.setThUseTime(request.getParameter("useTimeType"));
			com.setCtTime(CU.getSqlTime());
			comtService.save(com);
			return CU.goMsgPage(request, "评论成功！", "ok", "visitor/visitor_therapy.do?id="+therapy.getThId());	
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 变更用户积分
	 * @param user
	 * @param operation
	 */
	public void changeScore(Puser user,String operation) {
		Score score=scoreService.getScoreByName(operation);
		user.setPuScore(user.getPuScore()+Integer.parseInt(score.getScValue()));
		Operation op=new Operation();
		op.setScore(score);
		op.setOpTime(CU.getSqlTime());
		op.setPuser(user);
		opService.save(op);
		puserService.update(user);
	}
	
	/**
	 * 重置密码
	 * @return
	 */
	public String recoveryPassword(){
		String email=request.getParameter("email");
		Puser puser=puserService.findByEmail(email);
		if(puser!=null){
			//发送电子邮件
			CU.SendMail(email, "高友邦会员登陆信息找回", "亲爱的："+puser.getPuName()+"<br>您的登陆账号是："+puser.getPuAccount()+"<br>您的密码是："+puser.getPuPassword()+""
					+ "<br><b>为了您的账号安全请您登陆网站后尽快修改您的密码！</b> <br><a style='color:green' ' href='"+basePath+"visitorPage/index.jsp'  >访问高友邦首页>> </a>");
			return CU.goMsgPage(request, "您的登陆信息已经发送到您的邮箱，请尽快查看。", "ok", "visitorPage/index.jsp");
		}else{
			return CU.goMsgPage(request, "该邮箱没有绑定的账号", "err", "visitorPage/recoveryPassword.jsp");
		}
	}
	
	
	
	public String serch(){
		String serchType=request.getParameter("serchType");
		String keyWord=request.getParameter("keyWord");
		request.setAttribute("keyWord", keyWord);
		if(keyWord.equals("")){//没有输入类容
			
			return "serch";
		
		}else if(serchType.equals("1")){//文章
			
		  List<Article> list=artService.findByKeyWrod(keyWord);
		  request.setAttribute("list", list);
			return "serchArticle";
			
		}else if(serchType.equals("2")){//用户
			
			List<Puser> list=puserService.findByKeyWord(keyWord);
			request.setAttribute("list", list);
			return "serchUser";
			
		}else if(serchType.equals("3")){//药品
			
			List<Medicines> list=medicinesService.findByKeyWord(keyWord);
			request.setAttribute("list", list);
			return "serchMedicine";
			
		}else if(serchType.equals("4")){//疗法
			
			List<Therapy> list=therapytService.findByKeyWord(keyWord);
			request.setAttribute("list", list);
			return "serchTherapy";
			
		}
		return "serch";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
